package cn.unknowpupil.init.system;

import cn.hutool.core.convert.Convert;
import cn.unknowpupil.init.common.resopnse.ResultResponse;
import cn.unknowpupil.init.domain.gen.GenTable;
import cn.unknowpupil.init.domain.gen.GenTableColumn;
import cn.unknowpupil.init.service.gen.IGenTableColumnService;
import cn.unknowpupil.init.service.gen.IGenTableService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created at 2020-11-30 by  w10g <br>
 * Initialize GenTable  ... <br>
 * 代码生成业务表 视图浏览层处理
 *
 * @author unknowpupil
 * @since 0.0.1
 */

@Api(tags = {"代码生成业务表模块"}, value = "GenTable")
@RestController
@RequestMapping(value = "admin/tool/gen")
@RequiredArgsConstructor
public class GenTableController {

    private final IGenTableService genTableService;


    private final IGenTableColumnService genTableColumnService;

    /**
     * 查询代码生成列表
     */
    @GetMapping("list/{current}/{size}")
    public ResultResponse genList(@PathVariable("current") int current, @PathVariable("size") int size, GenTable genTable) {

        IPage<GenTable> list = genTableService.page(current, size, genTable);
        return ResultResponse.buildSuccess(list);
    }

    /**
     * 修改代码生成业务
     */
    @GetMapping(value = "/{tableId}")
    public ResultResponse getInfo(@PathVariable Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("info", table);
        map.put("rows", list);
        return ResultResponse.buildSuccess(map);
    }

    /**
     * 查询数据库列表
     */
    @GetMapping("/db/list/{current}/{size}")
    public ResultResponse dataList(@PathVariable("current") int current, @PathVariable("size") int size, GenTable genTable) {
        IPage<GenTable> list = genTableService.selectDbTableList(current, size, genTable);
        return ResultResponse.buildSuccess(list);
    }

    /**
     * 查询数据表字段列表
     */
    @GetMapping(value = "/column/{tableId}/{current}/{size}")
    public ResultResponse columnList(@PathVariable("tableId") Long tableId, @PathVariable("current") int current, @PathVariable("size") int size) {

        IPage<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId, current, size);

        return ResultResponse.buildSuccess(list);
    }

    /**
     * 导入表结构（保存）
     */
    @PostMapping("/importTable")
    public ResultResponse importTableSave(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        genTableService.importGenTable(tableList);
        return ResultResponse.success("导入表结构");
    }

    /**
     * 修改保存代码生成业务
     */
    @PutMapping
    public ResultResponse editSave(@Validated @RequestBody GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return ResultResponse.success("修改保存代码生成业务");
    }

    /**
     * 删除代码生成
     */
    @DeleteMapping("/{tableIds}")
    public ResultResponse remove(@PathVariable Long[] tableIds) {
        genTableService.delete(tableIds);
        return ResultResponse.success("删除代码生成");
    }

    /**
     * 预览代码
     */
    @GetMapping("/preview/{tableId}")
    public ResultResponse preview(@PathVariable("tableId") Long tableId) throws IOException {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return ResultResponse.buildSuccess(dataMap);
    }

    /**
     * 生成代码（下载方式）
     */
    @GetMapping("/download/{tableName}")
    public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
        byte[] data = genTableService.downloadCode(tableName);
        genCode(response, data);
    }

    /**
     * 生成代码（自定义路径）
     */
    @GetMapping("/genCode/{tableName}")
    public ResultResponse genCode(@PathVariable("tableName") String tableName) {
        genTableService.generatorCode(tableName);
        return ResultResponse.success("代码生成");
    }

    /**
     * 同步数据库
     */
    @GetMapping("/synchDb/{tableName}")
    public ResultResponse synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return ResultResponse.success("同步成功");
    }

    /**
     * 批量生成代码
     */
    @GetMapping("/batchGenCode")
    public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genTableService.downloadCode(tableNames);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"init.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
